package com.mrjy.common.solr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import com.mrjy.common.entity.SolrEntity;
import com.mrjy.common.util.SolrUtil;

/**
 * 操作solr实例
 * @author csshui
 *
 */
public class SolrServerClient {	

	@Autowired  
    private HttpSolrClient httpSolrClient;

	public void add(Object obj) throws Exception {
        this.httpSolrClient.addBean(obj); //添加数据到solr服务器
        this.httpSolrClient.commit(); //提交
    }
	
	public void addDoc(SolrInputDocument doc) throws Exception {
        this.httpSolrClient.add(doc); //添加数据到solr服务器
        this.httpSolrClient.commit(); //提交
    }

    public void deleteByIds(List<String> ids) throws Exception {
        this.httpSolrClient.deleteById(ids);
        this.httpSolrClient.commit(); //提交
    }
    
    public void deleteById(String id) throws Exception {
        this.httpSolrClient.deleteById(id);
        this.httpSolrClient.commit(); //提交
    }
    /**
     * 根据关键词 查询问题内容和
     * @param keywords 检索关键词(单个)
     * @param page 页数
     * @param rows 条数
     * @return 返回List<QuestionInfoSolrEntity> 问题的实体类list
     * @throws Exception
     */
//    public List<SolrEntity> questionSearch(String keywords, Integer page, Integer rows
//    		,Boolean isHighlight) throws Exception {
//        SolrQuery solrQuery = new SolrQuery(); //构造搜索条件
//        solrQuery.setQuery("questionContent:*"+keywords + "*" ); //搜索关键词
//        //solrQuery.setFilterQueries("questionContent:*"+keywords + "*"); //搜索关键词
//        solrQuery.setFields("id","questionId", "questionContent") ;
//        // 设置分页 start=0就是从0开始，，rows=5当前返回5条记录，第二页就是变化start这个值为5就可以了。
//        solrQuery.setStart((Math.max(page, 1) - 1) * rows);
//        solrQuery.setRows(rows);
//        
//        //设置高亮
//        if(isHighlight){
//        	 solrQuery.setHighlight(true);//分片使用，也就是检索出文件的部分内容。显示
//             solrQuery.addHighlightField("questionContent");//添加要进行高亮查询的字段名称
//             solrQuery.setHighlightSimplePre("<font color='#5BC9BE'>");
//             solrQuery.setHighlightSimplePost("</font >");
//             
//             //solrQuery.setHighlightFragsize(150);
//        }
//
//        // 执行查询
//        QueryResponse queryResponse = this.httpSolrClient.query(solrQuery);
//        SolrDocumentList docs = queryResponse.getResults();
//        List<SolrEntity> qis = null;
//        if( docs.getNumFound() != 0l){
//        	qis = (List<SolrEntity>) SolrUtil.SolrDocumentList2BeanList(docs, SolrEntity.class );
//        	
//        	if(isHighlight){
//        		// 第一个Map的键是文档的ID，第二个Map的键是高亮显示的字段名 
//                Map<String, Map<String, List<String>>> map = queryResponse.getHighlighting(); 
//                //System.out.println("map的内容： " + map); //用于测试map中的值 
//                for(int i = 0; i < qis.size() ; i++){
//                	SolrEntity qise = qis.get(i) ;
//                	qise.setQuestionContent(map.get(qise.getId()).get("questionContent").get(0));
//                }
//        	}
//        	
//        }
//        
//        return qis;
//    }
    
    /**
     * 
     * @param keywords 用户输入的关键词
     * @param type 0--课程   1--明师   2--问答  
     * @param page
     * @param rows
     * @param isHighlight 是否高亮
     * @return
     * @throws Exception
     */
    public Map<String, Object> doSearch(String keywords, Integer type, Integer page, Integer rows
    		,Boolean isHighlight) throws Exception {
    	Map<String, Object> map = new HashMap<String, Object>();
        SolrQuery solrQuery = new SolrQuery(); //构造搜索条件
        //过滤用户输入的关键词
        keywords = keywords.replace("?", "").replace("^", "")
        .replace("*", "").replace(":", "").replace("~", "").replace("(", "")
        .replace(")", "").replace("[", "").replace("]", "").replace("{", "")
        .replace("}", "").replace("\"", "").trim();
        keywords = StringUtils.deleteWhitespace(keywords);//去掉全部空格
        
        String q = "";
        if (type == null) {
        	//q = "keywords:"+keywords;
        	q = "videoName:"+keywords+" OR videoDesc:"+keywords+" OR videoTypes:"+keywords+" OR videoTeacher:"+keywords
        			+" OR coursePackageName:"+keywords+" OR coursePackageDesc:"+keywords
        			+" OR coursePackageTypes:"+keywords +" OR coursePackageTeacher:"+keywords
        			+" OR teacherName:"+keywords+" OR teacherDesc:"+keywords+" OR teacherTypes:"+keywords
        			+" OR questionContent:"+keywords+" OR questionDesc:"+keywords
					+" OR commentContent:"+keywords+" OR questionTypes:"+keywords;
        }else if (type.intValue() == 0) {
        	q = "videoName:"+keywords+" OR videoDesc:"+keywords+" OR videoTypes:"+keywords+" OR videoTeacher:"+keywords
        			+" OR coursePackageName:"+keywords+" OR coursePackageDesc:"+keywords
        			+" OR coursePackageTypes:"+keywords +" OR coursePackageTeacher:"+keywords;
		}else if (type.intValue() == 1) {
			q = "teacherName:"+keywords+" OR teacherDesc:"+keywords+" OR teacherTypes:"+keywords;
		}else if (type.intValue() == 2) {
			q = "questionContent:"+keywords+" OR questionDesc:"+keywords
					+" OR commentContent:"+keywords+" OR questionTypes:"+keywords;
		}
        solrQuery.setQuery(q); //搜索关键词
        // 设置分页 start=0就是从0开始，，rows=5当前返回5条记录，第二页就是变化start这个值为5就可以了。
        solrQuery.setStart((Math.max(page, 1) - 1) * rows);
        solrQuery.setRows(rows);
//        solrQuery.set("defType","dismax");  
//        solrQuery.set("qf","videoName^20 videoDesc^10 videoTypes ^10 videoTeacher^10 "
//        		+ "coursePackageName^20 coursePackageDesc^10 coursePackageTypes^10 coursePackageTeacher^10 "
//        		+ "teacherName^20 teacherDesc^10 teacherTypes^10 "
//        		+ "questionContent^20 questionDesc^20 commentContent^20 questionTypes^10 ");
//        
        //设置高亮
        if(isHighlight){
        	 solrQuery.setHighlight(true);//分片使用，也就是检索出文件的部分内容。显示
        	 solrQuery.addHighlightField("videoName");//添加要进行高亮查询的字段名称
    		 solrQuery.addHighlightField("videoDesc");
    		 solrQuery.addHighlightField("coursePackageName");
    		 solrQuery.addHighlightField("coursePackageDesc");
        	 solrQuery.addHighlightField("teacherName");
			 solrQuery.addHighlightField("teacherDesc");
        	 solrQuery.addHighlightField("questionContent");
			 solrQuery.addHighlightField("questionDesc");
			 solrQuery.addHighlightField("commentContent");
             solrQuery.setHighlightSimplePre("<font color='#47CC47'>");
             solrQuery.setHighlightSimplePost("</font >");
             
             //solrQuery.setHighlightFragsize(150);
        }

        // 执行查询
        QueryResponse queryResponse = this.httpSolrClient.query(solrQuery);
        // 结果集
        SolrDocumentList docs = queryResponse.getResults();
        List<SolrEntity> qis = null;
        if( docs.getNumFound() != 0l){
        	qis = (List<SolrEntity>) SolrUtil.SolrDocumentList2BeanList(docs, SolrEntity.class );
        	
        	if(isHighlight){
        		// 第一个Map的键是文档的ID，第二个Map的键是高亮显示的字段名 
                Map<String, Map<String, List<String>>> hlMap = queryResponse.getHighlighting(); 
                List<String> hlList = null;
                for(int i = 0; i < qis.size() ; i++){
                	SolrEntity qise = qis.get(i);
                	if (type == null) {
                		hlList = hlMap.get(qise.getId()).get("videoName");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setVideoName(hlList.get(0));
						}
						hlList = hlMap.get(qise.getId()).get("coursePackageName");
						if (hlList!=null && hlList.size()>0) {
                			qise.setCoursePackageName(hlList.get(0));
						}
	       				hlList = hlMap.get(qise.getId()).get("teacherName");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setTeacherName(hlList.get(0));
						}
                		hlList = hlMap.get(qise.getId()).get("teacherDesc");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setTeacherDesc(hlList.get(0));
						}
	       				hlList = hlMap.get(qise.getId()).get("questionContent");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setQuestionContent(hlList.get(0));
						}
                		hlList = hlMap.get(qise.getId()).get("questionDesc");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setQuestionDesc(hlList.get(0));
						}
                		hlList = hlMap.get(qise.getId()).get("commentContent");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setCommentContent(hlList.get(0));
						}
					}else if (type.intValue() == 0) {
                		hlList = hlMap.get(qise.getId()).get("videoName");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setVideoName(hlList.get(0));
						}
						hlList = hlMap.get(qise.getId()).get("coursePackageName");
						if (hlList!=null && hlList.size()>0) {
                			qise.setCoursePackageName(hlList.get(0));
						}
	       			}else if (type.intValue() == 1) {
	       				hlList = hlMap.get(qise.getId()).get("teacherName");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setTeacherName(hlList.get(0));
						}
                		hlList = hlMap.get(qise.getId()).get("teacherDesc");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setTeacherDesc(hlList.get(0));
						}
	       			}else if (type.intValue() == 2) {
	       				hlList = hlMap.get(qise.getId()).get("questionContent");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setQuestionContent(hlList.get(0));
						}
                		hlList = hlMap.get(qise.getId()).get("questionDesc");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setQuestionDesc(hlList.get(0));
						}
                		hlList = hlMap.get(qise.getId()).get("commentContent");
                		if (hlList!=null && hlList.size()>0) {
                			qise.setCommentContent(hlList.get(0));
						}
	       			}
                }
        	}
        }
        List<SolrEntity> courseList = new ArrayList<>();
        List<SolrEntity> teacherList = new ArrayList<>();
        List<SolrEntity> QAList = new ArrayList<>();
        if (qis!=null && qis.size()>0) {
        	for (SolrEntity solrEntity : qis) {
        		if (StringUtils.isNotBlank(solrEntity.getVideoName()) 
        				|| StringUtils.isNotBlank(solrEntity.getCoursePackageName())) {
        			if (type == null && courseList.size()==3) {
        				continue;
        			}
        			courseList.add(solrEntity);
        		}else if (StringUtils.isNotBlank(solrEntity.getTeacherName())) {
        			if (type == null && teacherList.size()==3) {
        				continue;
        			}
        			teacherList.add(solrEntity);
        		}else if (StringUtils.isNotBlank(solrEntity.getQuestionContent()) 
        				|| StringUtils.isNotBlank(solrEntity.getCommentContent())) {
        			if (type == null && QAList.size()==3) {
        				continue;
        			}
        			QAList.add(solrEntity);
        		}
        	}
		}
        
        map.put("courseList", courseList);
        map.put("teacherList", teacherList);
        map.put("QAList", QAList);
        map.put("numFound", docs.getNumFound());
        return map;
    }
    
    /**
     * @param keywords 标签  逗号分隔
     * @param type 0-视频  1-明师   21-语音回答   22-文字回答
     * @param page
     * @param rows
     * @param isHighlight
     * @return
     * @throws Exception
     */
    public Map<String, Object> doRecommend(String keywords,String type, Integer page, Integer rows
    		,Boolean isHighlight) throws Exception {
    	Map<String, Object> map = new HashMap<String, Object>();
        SolrQuery solrQuery = new SolrQuery(); //构造搜索条件
        String lables [] = null ;
        //过滤用户输入的关键词
        if(StringUtils.isNotBlank(keywords)){
        	keywords = keywords.replace("?", "").replace("^", "")
	        .replace("*", "").replace(":", "").replace("~", "").replace("(", "")
	        .replace(")", "").replace("[", "").replace("]", "").replace("{", "")
	        .replace("}", "").replace("\"", "").trim();
	        keywords = StringUtils.deleteWhitespace(keywords);//去掉全部空格
	        
	        lables = keywords.split(",");
        }else{
        	keywords = "*:*" ;
        }
        if(lables != null){
        	solrQuery.setQuery(lables[lables.length-1]); //搜索关键词
        }else{
        	solrQuery.setQuery(keywords); //搜索关键词
        }
        
        // 设置分页 start=0就是从0开始，，rows=5当前返回5条记录，第二页就是变化start这个值为5就可以了。
        solrQuery.setStart((Math.max(page, 1) - 1) * rows);
        solrQuery.setRows(rows);
          
        //返回视频
        if (type.startsWith("0")) {
        	if(lables != null){
        		String[] filterQueries = new String[lables.length-1];
        		for(int i = 0 ; i<lables.length-1; i++ ){
        			filterQueries[i] = "videoTypes:" + lables[i];
        		}
                solrQuery.setFilterQueries(filterQueries);
        	}
        	
        	solrQuery.set("defType","dismax");
        	solrQuery.set("qf","sortField^10.0 videoName^5.0 videoDesc^1.0 videoTypes^1.0");
        }
        //返回明师
        if (type.startsWith("1")) {
        	//没有语音回答权限
        	if (type.equals("10")) {
        		solrQuery.setFilterQueries("recordAuthority:0");
        	}else if (type.equals("11")) {//有语音回答权限
        		solrQuery.setFilterQueries("recordAuthority:1");
        	}else{
        		solrQuery.set("defType","dismax");
            	solrQuery.set("qf","sortField^10.0 teacherName^8.0 teacherTypes^5.0 teacherDesc^1.0 ");
        	}
		}
        //返回问答(语音+文字）
        if (type.startsWith("2")) {
        	if(lables != null){
        		String[] filterQueries = new String[lables.length-1];
        		for(int i = 0 ; i<lables.length-1; i++ ){
        			filterQueries[i] = "questionTypes:" + lables[i];
        		}
                solrQuery.setFilterQueries(filterQueries);
        	}
        	//语音
        	if (type.equals("21")) {
        		solrQuery.setFilterQueries("recordName:*");//筛选出recordName不为null的
        	}
        	//文字
        	if (type.equals("22")) {
        		solrQuery.setSort("replyType", ORDER.desc);
        		solrQuery.setFilterQueries("-recordName:*");//筛选出recordName为null的
        	}
        	solrQuery.set("defType","dismax");
        	solrQuery.set("qf","sortField^10.0 commentContent^5.0 questionContent^1.0 questionDesc^1.0 questionType^1.0");
		}
        
        // 执行查询
        QueryResponse queryResponse = this.httpSolrClient.query(solrQuery);
        // 结果集
        SolrDocumentList docs = queryResponse.getResults();
        List<SolrEntity> qis = null;
        if( docs.getNumFound() != 0l){
        	qis = (List<SolrEntity>) SolrUtil.SolrDocumentList2BeanList(docs, SolrEntity.class );
        }
        
        map.put("rows", qis);
        map.put("numFound", docs.getNumFound());
        return map;
    }
    
    /**
     * 
     * @param keywords 关键词
     * @param page
     * @param rows
     * @param isHighlight
     * @return
     * @throws Exception
     */
    public Map<String, Object> doRecommend2(String keywords, Integer page, Integer rows
    		,Boolean isHighlight) throws Exception {
    	Map<String, Object> map = new HashMap<String, Object>();
        SolrQuery solrQuery = new SolrQuery(); //构造搜索条件
        //过滤用户输入的关键词
        if(StringUtils.isNotBlank(keywords)){
        	keywords = keywords.replace("?", "").replace("^", "")
	        .replace("*", "").replace(":", "").replace("~", "").replace("(", "")
	        .replace(")", "").replace("[", "").replace("]", "").replace("{", "")
	        .replace("}", "").replace("\"", "").trim();
	        keywords = StringUtils.deleteWhitespace(keywords);//去掉全部空格
        }else{
        	keywords = "*:*" ;
        }
        
        solrQuery.setQuery(keywords); //搜索关键词
        // 设置分页 start=0就是从0开始，，rows=5当前返回5条记录，第二页就是变化start这个值为5就可以了。
        //全字段匹配
        solrQuery.set("df", "allField");
        String[] filterQueries = {"-id:question_*","-id:coursePackage_*","-id:teacher_*","-commentContent:*"};
        solrQuery.setFilterQueries(filterQueries);
        solrQuery.setStart((Math.max(page, 1) - 1) * rows);
        solrQuery.setRows(rows);
        
        // 执行查询
        QueryResponse queryResponse = this.httpSolrClient.query(solrQuery);
        // 结果集
        SolrDocumentList docs = queryResponse.getResults();
        List<SolrEntity> qis = null;
        if( docs.getNumFound() != 0l){
        	qis = (List<SolrEntity>) SolrUtil.SolrDocumentList2BeanList(docs, SolrEntity.class );
        }
        
        map.put("rows", qis);
        map.put("numFound", docs.getNumFound());
        return map;
    }

}
